package org.erepublik.company.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;

import javax.xml.bind.JAXBException;

import org.erepublik.company.Company;
import org.erepublik.company.ECountry;
import org.erepublik.company.generated.CompanyT;
import org.erepublik.company.utils.WebpageReader;
import org.erepublik.company.xml.XMLParsersers;

/**
 * Zwraca lokalizacje podanej firmy z internetu
 * 
 * @author Kacper Gorski 'Railman' railman85@gmail.com
 */
public class InternetCompanyCountryService implements ICompanyCountryService {

	private HashMap<CompanyId, Company> companies = new HashMap<CompanyId, Company>();

	public Company getLocationOfCompanyById(int id) {
		CompanyId companyId = new CompanyId(id);
		if (companies.get(companyId) != null)
			return companies.get(companyId);

		Company country = getCountryFromInternet(id);
		companies.put(companyId, country);
		return country;
	}

	private Company getCountryFromInternet(int id) {

		try {
			System.out.println("parsuje firme o id=" + id);
			InputStream stream = WebpageReader.getStreamToIrl("http://api.erepublik.com/v2/feeds/companies/" + id);
			CompanyT company;
			try {
				company = XMLParsersers.parseCompany(stream);
			} catch (JAXBException e) {
				e.printStackTrace();
				return null;
			}

			Company country = new Company(id, new Date().getTime(), ECountry.getCountryByName(company.getCountry().getName()),
					company.getName());
			return country;

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

}

class CompanyId {
	private int id;

	public CompanyId(int id) {
		this.id = id;
	}

	public int getId() {
		return id;
	}

	@Override
	public int hashCode() {
		return id;
	}

	@Override
	public boolean equals(Object o) {
		if (o instanceof CompanyId) {
			return ((CompanyId) o).getId() == getId();
		} else
			return false;
	}

}